package com.fanghuyun.iswaf.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import com.fanghuyun.iswaf.common.SysConfig;
import com.fanghuyun.iswaf.util.RC4;
import com.fanghuyun.iswaf.util.StringUtil;

public class Action {
	
	Logger logger = Logger.getLogger("iswaf.client");
	
	public Map<String,Object> getRequestMap(String str){
		Map<String,Object> map = new HashMap<String, Object>();
		for(String s:str.split("&")){
			if(s.indexOf("=")!=-1){
				map.put(s.substring(0,s.indexOf("=")),s.substring(s.indexOf("=")+1,s.length()));
			}else{
				map.put(s, null);
			}
		}
		return map;
	}

	public void runApi(HttpServletRequest request,HttpServletResponse response) throws Exception{
		Map<String,Object> result = new HashMap<String, Object>();
		PrintWriter out = response.getWriter();
		try {
			SysConfig sc = new SysConfig();
			Properties properties = sc.getSysConfigProperties();
			String rkey = properties.getProperty("system.rc4_key");
			if(DigestUtils.md5Hex(rkey).equals(request.getParameter("connect_key"))){
				Map<String,Object> map = getRequestMap(RC4.decry_RC4(new String(new BASE64Decoder().decodeBuffer(request.getParameter("data"))), rkey));
				if(map.containsKey("action")&&StringUtil.isNotEmpty(map.get("action"))){
					JSONObject json = (JSONObject) JSONSerializer.toJSON((String)map.get("args"));
					if("info".equals(map.get("action"))){
						result = AppInfo.info(json,request);
					}
				}else{
					logger.error("api reuqest action error");
				}
			}
			out.println(new BASE64Encoder().encode(RC4.encry_RC4_byte(new BASE64Encoder().encode(new String(JSONObject.fromObject(result).toString()).getBytes()), rkey)));
//			out.println(result.get("out"));
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(e);
		}
	}
	
	
	public static void main(String[] args) throws IOException {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("key", "ok");
		map.put("value", "1&s=b");
		map.put("test", "测试a?");
		Action a = new Action();
		Map<String,Object> rs = a.getRequestMap("action=info&args="+new BASE64Encoder().encode(new String(JSONObject.fromObject(map).toString()).getBytes()));
		System.out.println("action:"+rs.get("action"));
		System.out.println("args:"+new String(new BASE64Decoder().decodeBuffer((String)rs.get("args"))));
		JSONObject json = (JSONObject) JSONSerializer.toJSON(new String(new BASE64Decoder().decodeBuffer((String)rs.get("args"))));
		System.out.println(json.get("test"));
	}
	
}
